package controller;

import java.io.IOException;
import java.util.ArrayList;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import model.News;
import service.PutCache;

import com.googlecode.objectify.Objectify;
import com.googlecode.objectify.ObjectifyService;
import com.googlecode.objectify.Query;

@SuppressWarnings("serial")
public class GoogleSearchServlet extends HttpServlet {

	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		
		String name = req.getParameter("q");
		req.setAttribute("name", name);
		
		try {
			ObjectifyService.register(News.class);
		} catch (Exception e) {
			e.printStackTrace();
		}
		Objectify objectify1 = ObjectifyService.begin();
		
		ArrayList<String> category = PutCache.getCacheList("category");
		
		ArrayList<Query<News>> listCate = new ArrayList<Query<News>>(); 
		if(category.size()>0)
		{
			for (int j = 0; j < category.size(); j++) {
				Query<News> list1 = objectify1.query(News.class).filter("categoryAlias", category.get(j)).order("-date").limit(5);
				listCate.add(list1);
			}
		}
		
		req.setAttribute("listCate", listCate);
		
		try {
			req.getRequestDispatcher("/gsearch.jsp").forward(req, resp);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
